package com.huawei.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by minshiwu on 2017/2/8.
 */
@WebFilter(filterName = "SessionFilter", urlPatterns = "/*")
public class SessionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        System.out.println("filter1-in");

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String url = request.getRequestURL().toString();
        if (url.contains("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

        HttpSession session = httpRequest.getSession();
        String uid = (String) session.getAttribute("user");

        System.out.println("uid ==" + uid);             //输出获得的session中属性的值
        if (uid == null) {
            servletRequest.getRequestDispatcher("index.html").forward(servletRequest, servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("filter1-out");
    }

    @Override
    public void destroy() {

    }
}
